package cc.linker.steplink.crm.merchanth5.controller.acs;

import cc.linker.steplink.crm.commons.constant.ContentConstant;
import cc.linker.steplink.crm.commons.domain.WxUser;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.merchanth5.commons.RequestFilter;
import cc.linker.steplink.crm.merchanth5.dao.MallBoomDao;
import cc.linker.steplink.crm.merchanth5.service.EnrollActiveService;
import cc.linker.steplink.crm.merchanth5.service.MallBoomService;
import cc.linker.steplink.crm.merchanth5.service.acs.JoinAgentService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.util.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 加盟代理
 * @Author: wuhangfeng
 * @Date: Created in 2019/9/23 19:42
 * @Version: 1.9.1
 */
@RestController
@RequestMapping("/acs/joinAgent")
public class JoinAgentController {

    @Autowired
    private JoinAgentService joinAgentService;

    @Autowired
    private SystemProperties systemProperties;

    @Autowired
    private HttpService httpService;

    @Autowired
    private MallBoomService mallBoomService;

    @Autowired
    private MallBoomDao mallBoomDao;

    @Autowired
    private EnrollActiveService enrollActiveService;

    @Autowired
    private RequestFilter requestFilter;

    /**
     * @Description: 获取加盟代理账户信息
     * @Return:
     * @Author: 锋
     * @Date: 2019/9/23 19:55
     * @Version: 1.9.1
     */
    @GetMapping("/getJoinAgentAccountInfo")
    public Map getJoinAgentAccountInfo(HttpServletRequest request) throws Exception {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        return joinAgentService.getJoinAgentAccountInfo(customerId, orgId);
    }

    /**
     * @Description: 获取加盟代理金日交易数据
     * @Return:
     * @Author: 锋
     * @Date: 2019/9/23 19:55
     * @Version: 1.9.1
     */
    @GetMapping("/getJoinAgentTodayTradeInfo")
    public Map getJoinAgentTodayTradeInfo(HttpServletRequest request) throws Exception {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        return joinAgentService.getJoinAgentTodayTradeInfo(customerId, orgId);
    }

    /**
     * 联盟商城列表
     *
     * @param request
     * @return
     */
    @GetMapping("/getMyShopGoods")
    public Object getMyShopGoods(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                                 @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                 @RequestParam(value = "customerId", required = false) String customerId,
                                 @RequestParam(value = "order", defaultValue = "time", required = false) String order,
                                 @RequestParam(value = "sort", defaultValue = "d", required = false) String sort,
                                 @RequestParam(value = "goodsType", defaultValue = "0", required = false) Integer goodsType,
                                 @RequestParam(value = "keyword", defaultValue = "", required = false) String keyword,
                                 @RequestParam(value = "catId", defaultValue = "0", required = false) Integer catId,
                                 @RequestParam(value = "catPid", defaultValue = "0", required = false) Integer catPid,
                                 HttpServletRequest request) throws Exception {
        Map<String, Object> sqlparam = new HashMap<>();
        String orgId = "";
        if (customerId == null) {
            WxUser wxUser =  requestFilter.getWxUser(request);
            customerId = wxUser.getCustomerId();
            orgId = wxUser.getOrgId();
        }
        sqlparam.put("customerId", customerId);
        if (pageIndex != null && pageIndex != 0) {
            sqlparam.put("pageIndex", (pageIndex - 1) * pageSize);
            sqlparam.put("pageSize", pageSize);
        }
        String forder = "upTime";
        if ("money".equals(order)) {
            forder = "moneyAmount";
        }
        String fsort = "DESC";
        if ("a".equals(sort)) {
            fsort = "ASC";
        }
        sqlparam.put("order", forder);
        sqlparam.put("sort", fsort);
        sqlparam.put("goodsType", goodsType);
        /**
         * @Modify: 锋
         * @Date: 2020/1/16 12:18
         * @Description: 懂小姐支持类目及关键字查询
         * @Version: 1.0.8
         */
        sqlparam.put("keyword", keyword);
        if(catId!=0){
            sqlparam.put("catId", catId);
        }else if(catPid!=0){
            sqlparam.put("catPid", catPid);
        }
        Integer daCount = joinAgentService.getMyShopGoodsCount(sqlparam);
        List<Map<String, Object>> allMallBoomGoodsList = joinAgentService.getMyShopGoods(sqlparam);
        for (Map<String, Object> map : allMallBoomGoodsList) {
            Long goodsType1 = (Long) map.get("goodsType");
            if (goodsType1 != null && goodsType1 == 9) {
                String goodsId = map.get("goodsId").toString();
                int enrollStatus = enrollActiveService.getEnrollStatus(goodsId);
                map.put("status", enrollStatus);
            } else {
                map.put("status", null);
            }
        }
        String url = systemProperties.getSync().getContentUrl() + ContentConstant.GET_ARTICLE_LIST_BY_IDS;
        List<Map<String, Object>> resList = new ArrayList<>();
        List<Map<String, Object>> daList = new ArrayList<>();
        StringBuilder articleIds = new StringBuilder();
        Map<String, Integer> reverseProfitModel = mallBoomDao.getReverseProfitModel(orgId);// 返润模式
        Integer serviceRatio;// 商品服务费占比例,eg:50
        Integer recommendRatio;// 商品推荐费占比例,eg:50
        if (reverseProfitModel == null) {
            // 机构没有设置返润模式
            serviceRatio = 50;
            recommendRatio = 50;
        } else {
            serviceRatio = reverseProfitModel.get("serviceRatio");
            recommendRatio = reverseProfitModel.get("recommendRatio");
        }
        for (Map<String, Object> val : allMallBoomGoodsList) {
            Long moneyAmount = (Long) val.get("moneyAmount");
            Long maxMoneyAmount = (Long) val.get("maxMoneyAmount");
            String rebateStr = (String) val.get("rebate");
            Double rebate = Double.valueOf(rebateStr);
            double v1 = rebate * serviceRatio.doubleValue() * moneyAmount.doubleValue() / 1000000;
            double v2 = rebate * recommendRatio.doubleValue() * moneyAmount.doubleValue() / 1000000;
            double v3 = rebate * maxMoneyAmount.doubleValue() / 10000;
            String s1 = new BigDecimal(v1).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
            String s2 = new BigDecimal(v2).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
            String s3 = new BigDecimal(v3).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
            if (v1 < v2) {
                val.put("min", s1);
                val.put("max", s3);
            } else {
                val.put("min", s2);
                val.put("max", s3);
            }
            if (!"".equals(val.get("articleId"))) {
                articleIds.append(",").append(val.get("articleId"));
            }
            Long skuMoney = mallBoomService.getSkuMoneyByGoodsId(val.get("goodsId").toString());
            if (null != skuMoney && skuMoney > 0) {
                val.put("moneyAmount", NumberUtils.fenToYuan(skuMoney));
            } else {
                val.put("moneyAmount", val.get("moneyAmount") == null ? "0" : NumberUtils.fenToYuan(Long.valueOf(val.get("moneyAmount").toString())));
            }
        }
        Map<String, Object> resData = new HashMap<String, Object>();
        resData.put("ids", articleIds.toString());
        JSONObject jsonObject = (JSONObject) JSONArray.toJSON(resData);
        String postres;
        if (goodsType == 0 || goodsType == 3) {
            // 商品类型 0 全部 1 商品 2 知识付费 3 文章 4 报名
            postres = httpService.doPost(url, jsonObject.toJSONString(), ContentConstant.JSON_HEADER);
        } else {
            postres = null;
        }
        if (null != postres) {
            Map res = (Map) JSON.parse(postres);
            if ("200".equals(res.get("code").toString())) {
                resList = (ArrayList) res.get("data");
                for (Map<String, Object> da : allMallBoomGoodsList) {
                    Map<String, Object> tmp = new HashMap<String, Object>();
                    tmp.put("goods", da);
                    Object arttmp = new HashMap<>();
                    for (Map<String, Object> va : resList) {
                        if (da.get("articleId").equals(va.get("id").toString())) {
                            arttmp = va;
                        }
                    }
                    tmp.put("news", arttmp);
                    daList.add(tmp);
                }
            } else {
                for (Map<String, Object> da : allMallBoomGoodsList) {
                    Map<String, Object> tmp = new HashMap<String, Object>();
                    tmp.put("goods", da);
                    Object arttmp = new HashMap<>();
                    tmp.put("news", arttmp);
                    daList.add(tmp);
                }
            }
        } else {
            for (Map<String, Object> da : allMallBoomGoodsList) {
                Map<String, Object> tmp = new HashMap<String, Object>();
                tmp.put("goods", da);
                Object arttmp = new HashMap<>();
                tmp.put("news", arttmp);
                daList.add(tmp);
            }
        }
        Map<String, Object> finalData = new HashMap<>();
        finalData.put("count", daCount);
        finalData.put("list", daList);
        return finalData;
    }

    /**
     * @param type       1 小b 2 我的小店
     * @param customerId 用户id
     */
    @PostMapping("/myStoreList")
    public Map<String, Object> myStoreList(@RequestBody Map<String, Object> params) {
        return joinAgentService.myStoreList(params);
    }

}
